<template>
    <el-card class="!border-none" shadow="never">
        <el-form ref="formRef" class="mb-[-16px]" :model="queryParams" :inline="true">
            <el-form-item>
                <el-input
                    class="w-[280px]"
                    v-model="queryParams.keyword"
                    placeholder="学号/姓名"
                    clearable
                    @keyup.enter="resetPage"
                />
            </el-form-item>

            <el-form-item>
                <el-cascader
                    class="w-[300px]"
                    v-model="queryParams.college"
                    @change="collegeChange"
                    :options="data"
                    placeholder="院系/班级"
                />
            </el-form-item>

            <el-form-item>
                <el-date-picker
                    v-model="queryParams.value2"
                    start-placeholder="选择开始时间"
                    end-placeholder="选择结束时间"
                    format="YYYY/MM/DD"
                    value-format="YYYY-MM-DD"
                    type="daterange"
                    class="w-[300px]"
                    placeholder="以创建时间范围筛选"
                    @change="dateChange"
                />
            </el-form-item>

            <el-form-item>
                <el-button type="primary" @click="resetPage">查询</el-button>
                <el-button @click="resetParams">重置</el-button>
            </el-form-item>
        </el-form>
    </el-card>
    <el-card class="!border-none" shadow="never">
        <el-space> 
          <el-button type="primary" @click="addUser">添加学生</el-button>
        <el-upload
            ref="upload"
            class="upload-demo"
            :action="`${config.baseUrl}${config.urlPrefix}/school.student/importStudent`"
            :limit="1"
            :headers="{
                token: `${userStore.token}`
            }"
            :show-file-list="false"
            :on-success="uploadSuccess"
        >
            <el-button>批量导入</el-button>
        </el-upload>
        <el-button>
            <a
                :href="`${config.baseUrl}/uploads/file/20250122/202501222152111b8120721.xlsx`"
                target="_blank"
                rel="noopener noreferrer"
            >
                下载模板
            </a></el-button
        >
        <el-button :disabled="isSelect.length === 0" @click="handleBatchDelete">批量删除</el-button>
        </el-space>
        <el-table
            stripe
            class="mt-2"
            size="large"
            v-loading="pager.loading"
            :data="pager.lists"
            @selection-change="handleSelectionChange"
        >
            <el-table-column type="selection" width="55" />
            <el-table-column label="学号" prop="sn" min-width="120">
                <template #default="{ row }"> {{ row.student_no }} </template>
            </el-table-column>
            <el-table-column label="姓名" min-width="100">
                <template #default="{ row }"> {{ row.real_name }} </template>
            </el-table-column>
            <el-table-column label="所属院系" prop="nickname" min-width="120">
                <template #default="{ row }"> {{ row.college.name }} </template>
            </el-table-column>
            <el-table-column label="所属班级" prop="mobile" min-width="100">
                <template #default="{ row }"> {{ row.classes.name }} </template>
            </el-table-column>
            <el-table-column label="班级学生（人）" prop="email" min-width="140">
                <template #default="{ row }">
                    {{ row.classes.student_num }}
                </template>
            </el-table-column>
            <el-table-column label="学生作品（个）" prop="inviter_name" min-width="140">
                <template #default="{ row }">
                    {{ row.classes.works_num }}
                </template>
            </el-table-column>
            <el-table-column label="账号状态" min-width="160">
                <template #default="{ row }">
                    <span v-if="row.status === 1" style="color: #1abc9c">• 启用</span>
                    <span v-else style="color: #f59a23">• 停用</span>
                </template>
            </el-table-column>
            <el-table-column label="创建时间" prop="created_at" min-width="180">
                <template #default="{ row }">
                    <div>{{ row.created_at }}</div>
                </template>
            </el-table-column>

            <el-table-column label="操作" min-width="200" fixed="right">
                <template #default="{ row }">
                    <div class="flex items-center">
                        <el-button link type="primary" @click="gotoDeatil(row)"> 查看 </el-button>
                        <el-button link plain type="primary" @click="handleEdit(row)">
                            编辑
                        </el-button>
                        <el-button
                            link
                            v-if="row.status == 1"
                            type="warning"
                            @click="BlackList(row)"
                        >
                            停止
                        </el-button>
                        <el-button
                            type="primary"
                            link
                            class="custom-btn custom-btn-start"
                            v-if="row.status == 2"
                            @click="BlackList(row)"
                        >
                            启用
                        </el-button>
                        <el-button type="danger" link @click="handleDelete(row)"> 删除 </el-button>
                    </div>
                </template>
            </el-table-column>
        </el-table>
        <div class="flex justify-end mt-4">
            <pagination
                v-model="pager"
                @change="getLists"
                background="red"
                layout="prev, pager, next, sizes"
            />
        </div>
    </el-card>

    <add-user-pop v-if="popShow" ref="addUserPopRef" @close="popClose" @submit="popConfirm" />
</template>
<script lang="ts" setup name="consumerLists">
import { usePaging } from '@/hooks/usePaging'
import { getStudentList, editStudent, getDepartmentList, delStudent } from '@/api/consumer'
import feedback from '@/utils/feedback'
import addUserPop from '../modals/addUserPop.vue'
import { useRequest } from 'vue-hooks-plus'
import useUserStore from '@/stores/modules/user'
const router = useRouter()
const userStore = useUserStore()
import config from '@/config'
import { ElMessage } from 'element-plus'

const uploadSuccess = () => {
    ElMessage({
        message: '批量导入成功',
        type: 'success'
    })
    getLists()
}

// 获取学院配置
const { data } = useRequest(async () => {
    const _Res = await getDepartmentList({
        page_no: 1, page_size: 9999 
    })

    const list: any = []

    _Res?.lists?.forEach((_item) => {
        if (_item?.classes && _item?.classes?.length > 0) {
            list.push({
                value: _item.id,
                label: _item.name,
                children: _item?.classes?.map((_item2) => {
                    return {
                        value: _item2.id,
                        label: _item2.name
                    }
                })
            })
        }
    })

    return list
})

//弹框ref
const addUserPopRef = shallowRef()
const popShow = ref(false)

const queryParams = reactive({
    keyword: '',
    created_start_date: '',
    created_end_date: '',
    college_id: '',
    classes_id: '',
    value2: '',
    college: ''
})

const collegeChange = (_data) => {
    queryParams.college_id = _data?.[0]
    queryParams.classes_id = _data?.[1]
}

const dateChange = (_data) => {
    queryParams.created_start_date = _data?.[0]
    queryParams.created_end_date = _data?.[1]
}

const isSelect = ref<number[]>([])

const { pager, getLists, resetPage, resetParams } = usePaging({
    fetchFun: getStudentList,
    params: queryParams
})
//打开创建用户弹框
const addUser = async () => {
    popShow.value = true
    await nextTick()
    addUserPopRef.value.open()
    //   addUserPopRef.value.setFormData({
    //     nickname: "测试",
    //   });
}

// 编辑
const handleEdit = async (data: any) => {
    popShow.value = true
    await nextTick()
    addUserPopRef.value.open()

    addUserPopRef.value.setFormData({
        ...data,
        password_confirm: data.password,
        status: data?.status === 1,
        college: [data?.college?.id, data?.classes?.id],
        id: data?.id
    })
}

//删除
const handleDelete = async (data: any) => {
    await feedback.prompt(`是否确定删除该学生？`, `操作确认`, {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        inputType: 'textarea',
        inputPlaceholder: '请输入备注',
        callback: async ({ action, value }: any) => {
            if (action == 'confirm') {
                console.log('确认了')
                try {
                    await delStudent({ ids: data?.id, remark: value })

                    getLists()
                } catch (error) {}
            } else {
            }
        },
        type: 'warning'
    })
}

const handleBatchDelete = async () => {
    // 当前选中数据
    const _select = isSelect.value
    await feedback.prompt(`是否确定删除选中学生？`, `操作确认`, {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        inputType: 'textarea',
        inputPlaceholder: '请输入备注',
        callback: async ({ action, value }: any) => {
            if (action == 'confirm') {
                console.log('确认了')
                try {
                    await delStudent({ ids: _select?.join(','), remark: value })

                    getLists()
                } catch (error) {}
            } else {
            }
        },
        type: 'warning'
    })
}

//黑名单
const BlackList = async (data) => {
    await feedback.prompt(
        `是否确定${data?.status == 1 ? '停用' : '启用'}该学生账号？`,
        `操作确认`,
        {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            inputType: 'textarea',
            inputPlaceholder: '请输入备注',
            callback: async ({ action, value }: any) => {
                if (action == 'confirm') {
                    console.log('确认了')
                    try {
                        await editStudent({
                            ...data,
                            status: data.status === 1 ? 2 : 1,
                            remark: value
                        })

                        getLists()
                    } catch (error) {}
                } else {
                }
            },
            type: 'warning'
        }
    )
}

//多选
const handleSelectionChange = (value: any) => {
    isSelect.value = value.map((item: any) => item.id)
}

//弹框关闭
const popClose = () => {
    popShow.value = false
}

const popConfirm = () => {
    getLists()
    popShow.value = false
}

onActivated(() => {
    getLists()
})

getLists()

// 路由跳转
const gotoDeatil = (data) => {
    router.push(`/user/student/detail?id=${data?.id}`)
}
</script>

<style lang="scss" scoped></style>
